package com.github.sbb.sherry.console.service.engine.config;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.sbb.sherry.console.dto.PageList;
import com.github.sbb.sherry.repository.entity.RuleParamConfig;
import com.github.sbb.sherry.repository.entity.RuleParamConfigExample;
import com.github.sbb.sherry.repository.entity.RulesEngine;
import com.github.sbb.sherry.repository.entity.RulesEngineExample;
import com.github.sbb.sherry.repository.mapper.RulesEngineMapper;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class RulesEngineConfigService {

  @Autowired
  private RulesEngineMapper rulesEngineMapper;

  public PageList<RulesEngine> pageList(int currentPage, Integer pageSize) {
    if (pageSize == null) {
      pageSize = 10;
    }

    Page<RuleParamConfig> page = PageHelper.startPage(currentPage, pageSize);

    RulesEngineExample example = new RulesEngineExample();

    List<RulesEngine> rulesParams = rulesEngineMapper.selectByExample(example);

    if (page.getPages() < currentPage) {
      rulesParams = new ArrayList<>();
    }

    return PageList.of(currentPage, pageSize, page.getTotal(), rulesParams);
  }

  public void add(RulesEngine rulesEngine) {
    rulesEngine.setId(null);
    rulesEngine.setExpansionConfig(null);
    rulesEngine.setStatus((short) 1);
    rulesEngineMapper.insertSelective(rulesEngine);
  }

  public RulesEngine getById(int id) {
    return rulesEngineMapper.selectByPrimaryKey(id);
  }

  public void changeEngineExpansionConfig(RulesEngine rulesEngine) {
    RulesEngine update = new RulesEngine();
    update.setId(rulesEngine.getId());
    update.setExpansionConfig(rulesEngine.getExpansionConfig());
    rulesEngineMapper.updateByPrimaryKeySelective(rulesEngine);
  }
}
